<template>
  <div class="wrap">
    <Title title='创建班级'/>
    <div class="fx">
      <el-input v-model="name" placeholder="请输入要创建的班级名字"></el-input>
      <el-button @click="createClass" class="btn">{{
        isCreate ? "创建" : "确定修改"
      }}</el-button>
    </div>
  </div>
</template>

<script>
import { warn, info, success, error } from "@/utils";
import { createClass, getOne, editClass } from "@/api/class";
import Title from "@/components/common/Title";
export default {
  data() {
    return {
      name: "",
      isCreate: true,
      id: "",
    };
  },
  components: {
    Title,
  },
  methods: {
    async createClass() {
      const name = this.name;
      if (!name) return info("请输入班级名字");
      if (this.isCreate) {
        // 创建
        const res = await createClass(name);
        if (res.code === 1) {
          // 修改成功
          success(res.msg);
        } else {
          // 修改失败
          warn(res.msg);
        }
      } else {
        // 修改
        const res = await editClass({ name, id: this.id });
        if (res.code === 1) {
          success(res.msg);
        } else {
          error(res.msg);
        }
      }
      this.name = "";
    },
  },
  async created() {
    const { id } = this.$route.query;
    if (id) {
      const res = await getOne(id);
      if (res.code === 1) {
        this.isCreate = false;
        this.id = id;
        this.name = res.data[0].name;
      } else {
        error(res.msg);
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.btn {
  margin-left: 10px;
}
</style>
